package com.hummingbird.portal.controller;


import com.github.pagehelper.PageInfo;
import com.hummingbird.portal.dto.QuestionDTO;
import com.hummingbird.portal.exception.ServiceException;
import com.hummingbird.portal.pojo.Question;
import com.hummingbird.portal.r.R;
import com.hummingbird.portal.service.IQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author -1E18
 * @since 2024-09-22
 */
@RestController
@RequestMapping("/portal/question")
@Slf4j
public class QuestionController {
    @Resource
    private IQuestionService questionService;

    // AuthenticationPrincipal : 将 Security 中的 UserDetails对象 注入给参数
    @GetMapping("/my")
    public R my(@AuthenticationPrincipal UserDetails user, Integer pageNum, Integer pageSize) {
        PageInfo<Question> myQuestions = questionService.getMyQuestions(user.getUsername(), pageNum, pageSize);
        return R.ok(myQuestions);
    }

    @PostMapping("/create")
    public R createQuestion(@RequestBody @Validated QuestionDTO questionDTO, BindingResult bindingResult, @AuthenticationPrincipal UserDetails user) {
        if (bindingResult.hasErrors()) {
            return R.unproecsableEntity(bindingResult.getFieldError().getDefaultMessage());
            // bindingResult.getAllErrors().forEach(error -> log.error(error.getDefaultMessage()));
        }
        log.info("question:{}", questionDTO);

        // 可以使用统一异常的处理 不写 try-catch
        questionService.saveQuestion(questionDTO, user.getUsername());
        return R.ok("创建问题成功");
    }

    @GetMapping("/teacher")
    @PreAuthorize("hasRole('ROLE_TEACHER')")    // 判权限
    public R teacher(@AuthenticationPrincipal UserDetails user, Integer pageNum, Integer pageSize) {
        PageInfo<Question> pageInfo = questionService.getQuestionsByTeacherName(user.getUsername(), pageNum, pageSize);
        return R.ok(pageInfo);
    }
}
